package com.kurumi.autoprint.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.kurumi.autoprint.enums.ResponseStatusEnum;
import com.kurumi.autoprint.mapper.mapper.print.PrintMrOrderMapper;
import com.kurumi.autoprint.pojo.print.PrintMrOrder;
import com.kurumi.autoprint.service.ChinaUmsPayService;
import com.kurumi.autoprint.util.DateUtil;
import com.kurumi.autoprint.util.ExceptionUtil;
import com.kurumi.autoprint.util.JsonUtil;
import com.kurumi.autoprint.util.PayUtil;
import com.kurumi.autoprint.util.QrUtil;
import com.kurumi.autoprint.util.Result;
import com.kurumi.autoprint.util.StringUtil;
import com.kurumi.autoprint.util.YinlianPayUtil;

@Service
public class ChinaUmsPayServiceImpl implements ChinaUmsPayService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${pay.ums.app_id}")
	private String appId;

	@Value("${pay.ums.app_key}")
	private String appKey;

	@Value("${pay.ums.mid}")
	private String mid;

	@Value("${pay.ums.tid}")
	private String tid;

	@Value("${pay.ums.msg_src_id}")
	private String msgSrcId;

	@Value("${pay.ums.msg_src}")
	private String msgSrc;

	@Value("${pay.ums.inst_mid}")
	private String instMid;

	@Value("${pay.ums.get_qrcode}")
	private String getQrcodeUrl;
	
	@Value("${pay.ums.query_netpay}")
	private String queryNetpayUrl;
	
	@Autowired
	private PrintMrOrderMapper PrintMrOrderMapper;

	@Override
	public Result getPayQsCode(PrintMrOrder printMrOrder, String ipAddress,String payUmTidBindIp) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		map.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
		// 商户号
		map.put("mid", mid);
		// 终端号
		map.put("tid", printMrOrder.getSendAccount());
		// 业务类型
		map.put("instMid", instMid);
		// 订单日期
		map.put("billDate", DateUtil.dateFormat("yyyy-MM-dd", new Date()));
		// 订单号
		String billNO = YinlianPayUtil.generateBillNo(msgSrcId);
		map.put("billNo", billNO);
		// 消息ID
		map.put("msgId", StringUtil.getId());
		// 消息ID
		//map.put("msgSrc", msgSrc);
		// 费用
		if("130521198909060772".equals(printMrOrder.getIdNumber())) {
			map.put("totalAmount", 1);
		}else {
			map.put("totalAmount", 1);
			
		}
		
		// 账单描述
		map.put("billDesc","自助打印收费");
		
		String entity = JsonUtil.objectToJson(map);
		
		printMrOrder.setOrderNum(billNO);
		
		//释放内存
		map = null;
		
		String authorization = null;
		
		try {
			authorization = YinlianPayUtil.getOpenBodySig(appId, appKey, entity);
		} catch (Exception e) {
			logger.error("生成付费二维码authorization失败:" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			return new Result(false, ResponseStatusEnum.YING_LIAN_AUTHORIZATION.getName(),
						null, ResponseStatusEnum.YING_LIAN_AUTHORIZATION.getValue());
		}

		Result result = YinlianPayUtil.send(getQrcodeUrl, authorization, entity);
		
		if (!result.isSuccess()) {
			return result;
		}
		
		String jsonData = (String) result.getData();
		
		Map codeMap = JsonUtil.jsonToPojo(jsonData, Map.class);
		
		String errMsg = MapUtils.getString(codeMap, "errMsg");
		logger.info("生成二维码errMsg=" + errMsg);
		
		if (MapUtils.getString(codeMap, "errCode").equals("SUCCESS")) {
			String billQRCode = MapUtils.getString(codeMap, "billQRCode");
			
			//生成二维码图片
			try {
				Map m = new HashMap();
				
				String qrBase64Str = QrUtil.qrBase64Str(billQRCode);
				m.put("qrBase64Str", qrBase64Str);
				m.put("orderNum", billNO);
				m.put("ipAddress", ipAddress);
				String printMachineIp = PayUtil.getPrintMachineIpByClientIp(ipAddress,payUmTidBindIp);
				m.put("printMachineIp", printMachineIp);
				String printerName = PayUtil.getPrinterNameByClientIp(ipAddress,payUmTidBindIp);
				m.put("printerName", printerName);
				return new Result(true, "成功", m, 200);
			} catch (Exception e) {
				logger.error("生成银联支付二维码图片异常, exceptionMsg=" +  ExceptionUtil.getStackTrace(e));
				return new Result(false, "生成银联支付二维码图片异常:" + ExceptionUtil.getStackTrace(e));
			}
		} else {
			return new Result(false, "调用银联生成二维码失败, 错误信息=" + errMsg, null, ResponseStatusEnum.YING_LIAN_CODE_ERROR.getValue());
		}
		
	
	}
	
	
	
	@Override
	public Result queryNetpayByOrderNo(String orderNum) throws Exception {
		
		List<PrintMrOrder> printMrOrderList = PrintMrOrderMapper.selectByOrderNum(orderNum);
		if(CollectionUtils.isEmpty(printMrOrderList)) {
			return new Result(false,"根据订单号查询不到订单!",404);
		}
		
		PrintMrOrder printMrOrder = printMrOrderList.get(0);
		
		
		
		
		Map<String, Object> params = new HashMap<>();
		params.put("msgId", StringUtil.getId());
		// 报文请求时间 格式yyyy-MM-dd HH:mm:ss
		params.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
		// 消息ID
		params.put("msgId", StringUtil.getId());
		// 商户号
		params.put("mid", mid);
		// 终端号
		params.put("tid", printMrOrder.getSendAccount());
		// 业务类
		params.put("instMid", instMid);
		// 订单号
		params.put("billNo", orderNum);
		// 订单时间
		params.put("billDate", DateUtil.dateFormat("yyyy-MM-dd", new Date()));

		// 参数信息
		String entity = JsonUtil.objectToJson(params);

		// 释放内存
		params = null;

		String authorization = null;

		try {
			authorization = YinlianPayUtil.getOpenBodySig(appId, appKey, entity);
		} catch (Exception e) {
			logger.error("根据订单号查询authorization失败:" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			return new Result(false, ResponseStatusEnum.YING_LIAN_AUTHORIZATION.getName(), null,
					ResponseStatusEnum.YING_LIAN_AUTHORIZATION.getValue());
		}
		
		Result result = YinlianPayUtil.send(queryNetpayUrl, authorization, entity);

		if (!result.isSuccess()) {
			return result;
		}

		String jsonData = (String) result.getData();

		Map<String,Object> codeMap = JsonUtil.jsonToPojo(jsonData, Map.class);
		

		String errCode = MapUtils.getString(codeMap, "errCode");
		logger.info("根据订单号查询支付结果:errCode=" + errCode);

		if (MapUtils.getString(codeMap, "errCode").equals("SUCCESS")) {
				String billStatus = MapUtils.getString(codeMap, "billStatus");
				
				return  new Result(true,"订单支付状态查询成功!",billStatus,200);
				
			
		}else {
			return new Result(false, "根据订单号无法找到指定账单, 错误信息=" + errCode, null,
					ResponseStatusEnum.BILL_NOT_EXIT.getValue());
		}
		

	}
	
	
	
	
	
	
	
	
	

}



